﻿
import com.kirillam.handy.core.HATObject;
import com.kirillam.handy.core.HATControlClip;

import com.kirillam.handy.events.HATEvent;

/**
* Sends pulse events at specific frame intervals.
* 
* @author Kirill Mourzenko
*/

class com.kirillam.handy.repeaters.HATFrameTimer extends HATObject
{
	
	private var interval	: Number;
	private var pulses		: Number;
	
	private var frames		: Number;
	
	
	/**
	 * Constructor
	 */
	
	public function HATFrameTimer() 
	{
		super();
	}
	
	
	/*
	 * Handles HATEvent.ENTER_FRAME sent by the control clip and sends puls events.
	 */
	
	private function onFrameEntered( e : HATEvent )
	{
		frames++;
		
		if ( frames >= interval ) {
			
			frames	= 0;
			pulses--;
			
			sendEvent( new HATEvent( HATEvent.PULSE ) );
			
			if ( pulses <= 0 ) {
				HATControlClip.instance.ignore( HATEvent.ENTER_FRAME, this );
				sendEvent( new HATEvent( HATEvent.STOP ) );
			}
		}
	}
	
	
	/**
	 * Starts the timer.
	 * 
	 * @param	interval	Number of frames between pulse events.
	 * @param	pulses		Number of pulses to make. If null then there's no limit on number of pulses.
	 */
	
	public function start( interval : Number, pulses : Number )
	{
		frames				= 0;
		
		if ( interval != null && interval > 1 ) {
			this.interval	= interval;
		} else {
			this.interval	= 1;
		}
		
		if ( pulses != null && pulses > -1 ) {
			this.pulses		= pulses;
		} else {
			this.pulses		= Number.POSITIVE_INFINITY;
		}
		
		HATControlClip.instance.handle( HATEvent.ENTER_FRAME, this, onFrameEntered );
	}
	
	
	/** Stops the timer. */
	
	public function kill()
	{
		HATControlClip.instance.ignore( HATEvent.ENTER_FRAME, this );
	}
	
	
	/** 
	 * Tells if the timer is running.
	 *
	 * @return	true if the timer is running, false otherwise.
	 */
	
	public function isActive() : Boolean
	{
		return HATControlClip.instance.hasHandler( HATEvent.ENTER_FRAME, this );
	}
}